package com.treeman.marker.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.treeman.marker.Marker;
import com.treeman.marker.Marker.MarkerType;

@Repository
public class MarkerDaoImpl implements MarkerDao {

	private static Logger log = Logger.getLogger(MarkerDaoImpl.class);

	private SessionFactory sessionFactory;

	@Autowired
	public MarkerDaoImpl(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session currentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public Long addMarker(Marker marker) {
		return (Long) currentSession().save(marker);
	}

	@Override
	public Marker getMarkerById(Long id) {
		return (Marker) currentSession().get(Marker.class, id);
	}

	@Override
	public List<Marker> getMarkersByType(MarkerType type) {

		@SuppressWarnings("unchecked")
		ArrayList<Marker> markers = (ArrayList<Marker>) currentSession()
				.createQuery("from Marker where type=type:")
				.setParameter("type", type).list();
		return markers;
	}

	@Override
	public void updateMarker(Marker marker) {
		currentSession().update(marker);
	}

	@Override
	public List<Marker> getMarkersByUserUsername(String username) {
		@SuppressWarnings("unchecked")
		ArrayList<Marker> markers = (ArrayList<Marker>) currentSession()
				.createCriteria(Marker.class).createCriteria("author")
				.add(Restrictions.eq("username", username)).list();
		return markers;
	}

	@Override
	public void deleteMarker(Long id) {
		Marker marker = (Marker) currentSession().load(Marker.class, id);
		currentSession().delete(marker);
	}

	@Override
	public void deleteMarker(Marker marker) {
		currentSession().delete(marker);
	}

}
